import sys
sys.path.append("../..")
import warnings
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, execjs, re
from urllib.parse import urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "安糖无忧-糖尿病并发症疾病"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "year": [str(i) for i in range(18, 76)],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": ["10000", "20000"],
            # 保障期限
            "expire": ["1年"],
            # 交费类型
            "payType": ["年交"]
        }
        for v in product(plan["year"], plan["gender"], plan["money"], plan["expire"], plan["payType"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self,dt=None):

        param = {
            "identityNo": {
                "age": int(dt["year"]),
                "sex": "1" if dt["gender"] == "M" else "2"
            },
            "scheme": "falx1" if dt["money"] == "10000" else "falx2"
        }
        yearCode = self.genYearCode( param )
        data = {
            "productCode": yearCode,
            "insuranceCode": "WVI",
            "isApplyCar": "0",
            "insuranceCount": "1",
            "backUp1": yearCode,
            "_action": "commonCalculateFee"
        }
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200:
            price = Helper.decimalParse( re.search(r"SUM_PREMIUM':'(.*?)'",r.text).group(1) )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data= {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])

    # 生成年龄代码
    def genYearCode(self,data=None):
        js = '''
        ;
        function changeProductCode(data) {
            identityNo = data["identityNo"];
            scheme = data["scheme"];
            if (identityNo) {
                var sex = identityNo["sex"];
                var age = identityNo["age"];
                if (null == scheme || undefined == scheme) {
                    return
                } else {
                    if (scheme == "falx1") {
                        if (sex == "2") {
                            if (age >= 18 && age <= 30) {
                                return "WVI_MB_ATWY_JCB_F_1";
                            } else if (age >= 31 && age <= 40) {
                                return "WVI_MB_ATWY_JCB_F_2";
                            } else if (age >= 41 && age <= 50) {
                                return "WVI_MB_ATWY_JCB_F_3";
                            } else if (age >= 51 && age <= 55) {
                                return "WVI_MB_ATWY_JCB_F_4";
                            } else if (age >= 56 && age <= 60) {
                                return "WVI_MB_ATWY_JCB_F_5";
                            } else if (age >= 61 && age <= 65) {
                                return "WVI_MB_ATWY_JCB_F_6";
                            } else if (age >= 66 && age <= 70) {
                                return "WVI_MB_ATWY_JCB_F_7";
                            } else if (age >= 71 && age <= 75) {
                                return "WVI_MB_ATWY_JCB_F_8";
                            }
                        } else if (sex == "1") {
                            if (age >= 18 && age <= 30) {
                                return "WVI_MB_ATWY_JCB_M_1";
                            } else if (age >= 31 && age <= 40) {
                                return "WVI_MB_ATWY_JCB_M_2";
                            } else if (age >= 41 && age <= 50) {
                                return "WVI_MB_ATWY_JCB_M_3";
                            } else if (age >= 51 && age <= 55) {
                                return "WVI_MB_ATWY_JCB_M_4";
                            } else if (age >= 56 && age <= 60) {
                                return "WVI_MB_ATWY_JCB_M_5";
                            } else if (age >= 61 && age <= 65) {
                                return "WVI_MB_ATWY_JCB_M_6";
                            } else if (age >= 66 && age <= 70) {
                                return "WVI_MB_ATWY_JCB_M_7";
                            } else if (age >= 71 && age <= 75) {
                                return "WVI_MB_ATWY_JCB_M_8";
                            }
                        }
                    } else if (scheme == "falx2") {
                        if (sex == "2") {
                            if (age >= 18 && age <= 30) {
                                return "WVI_MB_ATWY_AXB_F_1";
                            } else if (age >= 31 && age <= 40) {
                                return "WVI_MB_ATWY_AXB_F_2";
                            } else if (age >= 41 && age <= 50) {
                                return "WVI_MB_ATWY_AXB_F_3";
                            } else if (age >= 51 && age <= 55) {
                                return "WVI_MB_ATWY_AXB_F_4";
                            } else if (age >= 56 && age <= 60) {
                                return "WVI_MB_ATWY_AXB_F_5";
                            } else if (age >= 61 && age <= 65) {
                                return "WVI_MB_ATWY_AXB_F_6";
                            } else if (age >= 66 && age <= 70) {
                                return "WVI_MB_ATWY_AXB_F_7";
                            } else if (age >= 71 && age <= 75) {
                                return "WVI_MB_ATWY_AXB_F_8";
                            }
                        } else if (sex == "1") {
                            if (age >= 18 && age <= 30) {
                                return "WVI_MB_ATWY_AXB_M_1";
                            } else if (age >= 31 && age <= 40) {
                                return "WVI_MB_ATWY_AXB_M_2";
                            } else if (age >= 41 && age <= 50) {
                                return "WVI_MB_ATWY_AXB_M_3";
                            } else if (age >= 51 && age <= 55) {
                                return "WVI_MB_ATWY_AXB_M_4";
                            } else if (age >= 56 && age <= 60) {
                                return "WVI_MB_ATWY_AXB_M_5";
                            } else if (age >= 61 && age <= 65) {
                                return "WVI_MB_ATWY_AXB_M_6";
                            } else if (age >= 66 && age <= 70) {
                                return "WVI_MB_ATWY_AXB_M_7";
                            } else if (age >= 71 && age <= 75) {
                                return "WVI_MB_ATWY_AXB_M_8";
                            }
                        }
                    }
                }
            }
        };  
        '''
        cxt = execjs.compile( js )
        yearCode = cxt.call("changeProductCode",data )
        return ( yearCode )

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
